package login1;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/index1")
public class indexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf8");
        //判断当前用户是否已经登录
        //getSession参数为false，表示若没有创建过HttpSession，则返回null;
        //若创建过，则返回该对象
        HttpSession session = req.getSession(false);
        if(session == null) {
            resp.getWriter().write("很抱歉，尚未登录");
            //重定向到index
            resp.sendRedirect("login1");
            return;
        }
        //已登录过，就从Session中访问数据
        //这里由于getAttribute返回的是Object类型，所以这里需要强转成String
        String username = (String)session.getAttribute("username");
        int loginCount = (int)session.getAttribute("loginCount");
        resp.getWriter().write("欢迎回来:" + username + "~" + "<br>"
                + "您今日已经登录了:" + loginCount + "次");
    }
}
